<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\ShopCategoryApply;
use App\Repository\ShopCategoryApplyRepository;
use App\Service\ShopService;
use MongoDB\Driver\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiShopCategoryApplyController extends BaseController4Restful
{
    /**
     * @Route("/api/shopCategoryApplys", name="apiGetShopCategoryApplys",methods={"GET","POST"})
     */
    public function apiGetShopCategoryApplys(ShopCategoryApplyRepository $repository, Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $ShopCategoryApply ShopCategoryApply */
                $ShopCategoryApply = $this->createEntity($data, ShopCategoryApply::class);
                $this->myEm()->persist($ShopCategoryApply);
                $this->myEm()->flush();
                return $this->json_out(200, "创建成功", $ShopCategoryApply);
            default:
                if (!$page = $this->getParamRequired("page")) {
                    $page = 1;
                }
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page, $total, $limit);
                $list = $repository->findBy(array(), array(), $limit, $offset);
                return $this->json_out(200, "获取成功", $list);
        }
    }

    /**
     * @Route("/api/shopCategoryApplys/{id}", name="apiAddShopCategoryApplys",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateShopCategoryApplys(ShopCategoryApply $ShopCategoryApply, Request $request, ShopCategoryApplyRepository $repository, ShopService $shopService)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($ShopCategoryApply);
                $this->myEm()->flush();
                return $this->json_out(200, "已移除");
            case "PATCH":
            case "PUT":
                $this->myEm()->beginTransaction();
                try {
                    $isAll = $this->getParamRequired("isAll");
                    $isAll = true;
                    $shop = $ShopCategoryApply->getShop();
                    $startStatus = $ShopCategoryApply->getStatus();
                    $endStatus = $data["status"];
                    if ($isAll) {
                        //如果是批量更新需要先清空原有属性
                        if ($request->getMethod() == "PATCH" && $startStatus == 0 && $endStatus == 1) {
                            $cats = $shop->getCategories();
                            foreach ($cats as $cat) {
                                $shop->removeCategory($cat);
                            }
                        }
                        //执行批量操作，同时统计一下数据看是否合理
                        $ShopCategoryApplyList = $repository->findBy(array("shop" => $ShopCategoryApply->getShop(), "status" => $ShopCategoryApply->getStatus()));
                        foreach ($ShopCategoryApplyList as $ShopCategoryApply) {
                            /**@var $ShopCategoryApply ShopCategoryApply */
                            $ShopCategoryApply = $this->updateEntity($data, ShopCategoryApply::class, $ShopCategoryApply);
                            if ($request->getMethod() == "PATCH" && $startStatus == 0 && $endStatus == 1) {
                                //检查用户是否获得相应分类，如果没有就增加
                                $cats = $shop->getCategories();
                                if (!$cats->contains($ShopCategoryApply->getCategory())) {
                                    $shop->addCategory($ShopCategoryApply->getCategory());
                                }
                            }
                        }
                    } else {
                        /**@var $ShopCategoryApply ShopCategoryApply */
                        $ShopCategoryApply = $this->updateEntity($data, ShopCategoryApply::class, $ShopCategoryApply);
                        if ($request->getMethod() == "PATCH" && $startStatus == 0 && $endStatus == 1) {
                            //检查用户是否获得相应分类，如果没有就增加
                            $cats = $shop->getCategories();
                            if (!$cats->contains($ShopCategoryApply->getCategory())) {
                                $shop->addCategory($ShopCategoryApply->getCategory());
                            }
                        }
                    }

                    $this->myEm()->persist($shop);
                    $this->myEm()->persist($ShopCategoryApply);
                    $this->myEm()->flush();
                    //重新计算数据
                    $data = $shopService->getCategoryLimit($shop);
                    if ($data["cat1Cur"] > $data["cat1Max"] || $data["cat2Cur"] > $data["cat2Max"]) {
                        $this->myEm()->rollback();
                        return $this->json_out(400, "申请数量超出限制");
                    }
                } catch (Exception $exception) {
                    $this->myEm()->rollback();
                    return $this->json_out(500, "", $exception);
                }
                $this->myEm()->commit();
                return $this->json_out(200, "处理成功", $ShopCategoryApply);
                break;
            case "Get":
            default:
        }
        return $this->json_out(200, "获取成功", $ShopCategoryApply);
    }


    /**
     * @Route("/api/my/shopCategoryApplys", name="apiGetMyShopCategoryApplys",methods={"GET","POST"})
     */
    public function apiGetMyShopCategoryApplys(ShopCategoryApplyRepository $repository, Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $ShopCategoryApply ShopCategoryApply */
                $ShopCategoryApply = $this->createEntity($data, ShopCategoryApply::class);
                $this->myEm()->persist($ShopCategoryApply);
                $this->myEm()->flush();
                return $this->json_out(200, "创建成功", $ShopCategoryApply);
            default:
                $user = $this->needToBeUser();
                if (!$page = $this->getParamRequired("page")) {
                    $page = 1;
                }
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page, $total, $limit);
                $this->setGroups("app");
                $list = $repository->findBy(array("shop"=>$user->getShop()), array("id"=>"DESC"), $limit, $offset);
                return $this->json_out(200, "获取成功", $list);
        }
    }
}
